package com.ht.web360.base.config.data;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ht.web360.base.utils.ThreadLocalUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Configuration
public class MybatisPlusConfig {
    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MyMetaObjectHandler myMetaObjectHandler() {
        return new MyMetaObjectHandler();
    }

    public static class MyMetaObjectHandler implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            // 配置自动注入
            if (metaObject.hasSetter("createTime") && metaObject.getValue("createTime") == null) {
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            }
            if (metaObject.hasSetter("updateTime") && metaObject.getValue("updateTime") == null) {
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
            if (metaObject.hasSetter("creatorId") && metaObject.getValue("creatorId") == null) {
                this.strictInsertFill(metaObject, "creatorId", Long.class, ThreadLocalUtil.getUserId());
            }
            if (metaObject.hasSetter("updaterId") && metaObject.getValue("updaterId") == null) {
                this.strictInsertFill(metaObject, "updaterId", Long.class, ThreadLocalUtil.getUserId());
            }
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            if (metaObject.hasSetter("updateTime") && metaObject.getValue("updateTime") == null) {
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
            if (metaObject.hasSetter("updaterId") && metaObject.getValue("updaterId") == null) {
                this.strictInsertFill(metaObject, "updaterId", Long.class, ThreadLocalUtil.getUserId());
            }
        }
    }
}